define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'scanwork/qrcode_manager/index' + location.search,
                    add_url: 'scanwork/qrcode_manager/add',
                    edit_url: 'scanwork/qrcode_manager/edit',
                    del_url: 'scanwork/qrcode_manager/del',
                    multi_url: 'scanwork/qrcode_manager/multi',
                    table: 'qrcode_manager',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'allocation_id', title: __('分工ID'), operate: 'LIKE'},
                        {field: 'order_no', title: __('订单号'), operate: 'LIKE', formatter: function(value, row, index) {
                            return value || (row.allocation && row.allocation.order ? row.allocation.order.order_no : '');
                        }},
                        {field: 'product_name', title: __('产品名称'), operate: 'LIKE', formatter: function(value, row, index) {
                            return value || (row.allocation && row.allocation.model && row.allocation.model.product ? row.allocation.model.product.name : '');
                        }},
                        {field: 'model_name', title: __('产品型号'), operate: 'LIKE', formatter: function(value, row, index) {
                            return value || (row.allocation && row.allocation.model ? row.allocation.model.name : '');
                        }},
                        {field: 'process_name', title: __('工序名称'), operate: 'LIKE', formatter: function(value, row, index) {
                            return value || (row.allocation && row.allocation.process ? row.allocation.process.name : '');
                        }},
                        {field: 'employee_name', title: __('员工姓名'), operate: 'LIKE', formatter: function(value, row, index) {
                            return value || (row.allocation && row.allocation.user ? row.allocation.user.nickname : '');
                        }},
                        {field: 'quantity', title: __('分配数量'), align: 'center', formatter: function(value, row, index) {
                            return value || (row.allocation ? row.allocation.quantity : '');
                        }},
                        {field: 'qr_content', title: __('二维码数据'), formatter: function(value, row, index) {
                            if (value && value.length > 30) {
                                return value.substring(0, 30) + '...';
                            }
                            return value || '';
                        }},
                        {field: 'qr_image', title: __('二维码图片'), formatter: function(value, row, index) {
                            if (value) {
                                return '<img src="' + value + '" style="width: 50px; height: 50px;" onerror="this.src=\'/assets/img/noimage.png\'" />';
                            }
                            return '';
                        }},
                        {field: 'scan_count', title: __('扫码次数'), align: 'center'},
                        {field: 'status', title: __('状态'), searchList: {"0":__('未使用'),"1":__('已使用')}, formatter: function(value, row, index) {
                            var statusMap = {
                                '0': {text: '未使用', class: 'label-warning'},
                                '1': {text: '已使用', class: 'label-success'}
                            };
                            var status = statusMap[value] || {text: value, class: 'label-default'};
                            return '<span class="label ' + status.class + '">' + status.text + '</span>';
                        }},
                        {field: 'last_scan_time', title: __('最后扫码时间'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'createtime', title: __('创建时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('操作'), table: table, events: Table.api.events.operate, formatter: function(value, row, index) {
                            var table = this.table;
                            var options = table ? table.bootstrapTable('getOptions') : {};
                            var buttons = [];
                            buttons.push({
                                name: 'download',
                                text: __('下载'),
                                title: __('下载二维码'),
                                classname: 'btn btn-xs btn-info',
                                icon: 'fa fa-download',
                                url: 'scanwork/qrcode_manager/download/ids/{ids}',
                                callback: function (data) {
                                    // 直接下载，不需要刷新表格
                                }
                            });
                            buttons.push({
                                name: 'print',
                                text: __('打印'),
                                title: __('打印二维码'),
                                classname: 'btn btn-xs btn-success',
                                icon: 'fa fa-print',
                                url: 'scanwork/qrcode_manager/print/ids/{ids}',
                                callback: function (data) {
                                    // 直接打印，不需要刷新表格
                                }
                            });
                            return Table.api.formatter.operate.call(this, value, row, index, buttons);
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        scanstats: function () {
            // 加载统计数据
            $.get('scanwork/qrcode_manager/scanstats', function(data) {
                if (data.code === 1) {
                    var stats = data.data;
                    $('#total-qrcodes').text(stats.total_qrcodes);
                    $('#used-qrcodes').text(stats.used_qrcodes);
                    $('#unused-qrcodes').text(stats.unused_qrcodes);
                    $('#total-scans').text(stats.total_scans);
                    $('#today-scans').text(stats.today_scans);
                    
                    // 计算使用率
                    var usageRate = stats.total_qrcodes > 0 ? Math.round((stats.used_qrcodes / stats.total_qrcodes) * 100) : 0;
                    $('#usage-rate').text(usageRate);
                    $('#usage-progress').css('width', usageRate + '%');
                }
            });
        },
        generate: function () {
            // 生成二维码按钮事件
            $('.btn-generate').on('click', function() {
                var ids = Table.api.selectedids();
                if (ids.length === 0) {
                    Toastr.error('请选择要生成二维码的记录');
                    return;
                }
                if (ids.length > 1) {
                    Toastr.error('请选择单条记录生成二维码');
                    return;
                }
                
                Fast.api.ajax({
                    url: 'scanwork/qrcode_manager/generate',
                    data: {ids: ids[0]},
                    success: function(data) {
                        Toastr.success('二维码生成成功');
                        $("#table").bootstrapTable('refresh');
                    }
                });
            });
            Controller.api.bindevent();
        },
        batchgenerate: function () {
            // 批量生成二维码按钮事件
            $('.btn-batchgenerate').on('click', function() {
                var ids = Table.api.selectedids();
                if (ids.length === 0) {
                    Toastr.error('请选择要生成二维码的记录');
                    return;
                }
                
                Fast.api.ajax({
                    url: 'scanwork/qrcode_manager/batchGenerate',
                    data: {ids: ids},
                    success: function(data) {
                        Toastr.success(data.msg);
                        $("#table").bootstrapTable('refresh');
                    }
                });
            });
            Controller.api.bindevent();
        },
        regenerate: function () {
            // 重新生成二维码按钮事件
            $('.btn-regenerate').on('click', function() {
                var ids = Table.api.selectedids();
                if (ids.length === 0) {
                    Toastr.error('请选择要重新生成二维码的记录');
                    return;
                }
                if (ids.length > 1) {
                    Toastr.error('请选择单条记录重新生成二维码');
                    return;
                }
                
                Fast.api.ajax({
                    url: 'scanwork/qrcode_manager/regenerate',
                    data: {ids: ids[0]},
                    success: function(data) {
                        Toastr.success('二维码重新生成成功');
                        $("#table").bootstrapTable('refresh');
                    }
                });
            });
            Controller.api.bindevent();
        },
        download: function () {
            // 下载二维码按钮事件
            $('.btn-download').on('click', function() {
                var ids = Table.api.selectedids();
                if (ids.length === 0) {
                    Toastr.error('请选择要下载的二维码');
                    return;
                }
                if (ids.length > 1) {
                    Toastr.error('请选择单条记录下载二维码');
                    return;
                }
                
                window.open(Fast.api.fixurl('scanwork/qrcode_manager/download', {ids: ids[0]}));
            });
            Controller.api.bindevent();
        },
        batchdownload: function () {
            // 批量下载二维码按钮事件
            $('.btn-batchdownload').on('click', function() {
                var ids = Table.api.selectedids();
                if (ids.length === 0) {
                    Toastr.error('请选择要下载的二维码');
                    return;
                }
                
                Fast.api.ajax({
                    url: 'scanwork/qrcode_manager/batchDownload',
                    data: {ids: ids},
                    success: function(data) {
                        // 创建下载链接
                        var link = document.createElement('a');
                        link.href = data.url;
                        link.download = data.filename;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }
                });
            });
            Controller.api.bindevent();
        },
        print: function () {
            // 打印二维码按钮事件
            $('.btn-print').on('click', function() {
                var ids = Table.api.selectedids();
                if (ids.length === 0) {
                    Toastr.error('请选择要打印的二维码');
                    return;
                }
                if (ids.length > 1) {
                    Toastr.error('请选择单条记录打印二维码');
                    return;
                }
                
                window.open(Fast.api.fixurl('scanwork/qrcode_manager/print', {ids: ids[0]}));
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
